package com.wst.system.security.handler;


import com.wst.system.config.Constant;
import com.wst.system.config.cache.SysCacheServer;
import com.wst.system.security.config.JWTConfig;
import com.wst.system.security.config.ReflushJWTConfig;
import com.wst.system.security.entity.SelfUserEntity;
import com.wst.system.security.entity.SysUserTokenEntity;
import com.wst.system.server.service.SysUserTokenService;
import com.wst.system.util.JWTTokenUtil;
import com.wst.system.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/11 15:10
 * @since JDK 1.8
 */
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Autowired
    private SysCacheServer sysCacheServer;

    /**
     * 登录成功返回结果
     * @Author Sans
     * @CreateTime 2019/10/3 9:27
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        // 组装JWT
        SelfUserEntity selfUserEntity =  (SelfUserEntity) authentication.getPrincipal();
        log.info("{} 用户成功登录，现在开始签发token",selfUserEntity.getUsername());
        String token = JWTTokenUtil.createAccessToken(selfUserEntity);
        String reflushToken=JWTTokenUtil.createRefreshToken(selfUserEntity);
        log.info("给 {} 用户签发的token为 {}",selfUserEntity.getUsername(),token);
        token = JWTConfig.tokenPrefix + token;

        String sessionId=sysUserTokenService.getSessionId();
        String flushTokenStr=ReflushJWTConfig.tokenPrefix+reflushToken;
        // 封装返回参数
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code",200);
        resultData.put("msg", "登录成功");
        resultData.put(Constant.USER_TOKEN,token);
        resultData.put(Constant.REFLUSH_TOKEN, flushTokenStr);

        SysUserTokenEntity userToken=new SysUserTokenEntity();
        userToken.setUserid(selfUserEntity.getUserId().toString());
        userToken.setUsername(selfUserEntity.getUsername());
        userToken.setLogindate(new Date());
        userToken.setIsDisabled(true);
        userToken.setToken(token);
        userToken.setTokenType(Constant.USER_TOKEN);
        sysUserTokenService.save(userToken);

        SysUserTokenEntity flushToken=new SysUserTokenEntity();
        flushToken.setUserid(selfUserEntity.getUserId().toString());
        flushToken.setUsername(selfUserEntity.getUsername());
        flushToken.setLogindate(new Date());
        flushToken.setIsDisabled(true);
        flushToken.setToken(flushTokenStr);
        flushToken.setTokenType(Constant.REFLUSH_TOKEN);
        sysUserTokenService.save(flushToken);


        Cookie cookie = new Cookie(JWTConfig.tokenHeader, token);
        // 设置Cookie的其他属性（可选）
        cookie.setMaxAge(3600); // 设置Cookie的生命周期，单位为秒
        cookie.setPath("/"); // 设置Cookie的路径
        // 其他属性，如：cookie.setDomain("domain.com");
        // 将Cookie添加到响应中
        response.addCookie(cookie);
        ResultUtil.responseJson(response,resultData);
    }
}
